{CompositeDisposable} = require 'atom'
opn = require 'opn'

module.exports =

  subscriptions: null

  activate: ->
    @subscriptions = new CompositeDisposable
    @subscriptions.add atom.commands.add 'atom-text-editor',
      'open-in-browser:open', @openEditor.bind(this)
    @subscriptions.add atom.commands.add '.tree-view .file',
      'open-in-browser:open-tree-view', @openTreeView.bind(this)

  getFilePath: -> atom.workspace.getActiveTextEditor().getPath()

  openEditor: ->
    @open @getFilePath()

  openTreeView_v0: ({target}) ->
    @open target.dataset.path
  #
  openTreeView: ({target}) ->
    console.log "目标:", target
    console.log "数据集:", target.dataset
    console.log "路径:", target.dataset?.path
    if target.dataset?.path
      @open target.dataset.path
    else
      atom.notifications.addError "无效的文件路径", detail: "无法从树视图获取文件路径", dismissable: true
  #

  open_v0: (filePath) ->
    opn(filePath).catch (error) ->
      atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
      console.error error
  #
  open: (filePath) ->
    console.log "正在打开文件:", filePath
    if filePath
      opn(filePath).catch (error) ->
        atom.notifications.addError error.toString(), detail: error.stack or '', dismissable: true
        console.error error
    else
      atom.notifications.addError "无效的文件路径", detail: "文件路径为空或未定义", dismissable: true

  deactivate: ->
    @subscriptions?.dispose()
